<template>

  <div class="filter-container">

    <el-row>

      <el-col span="3">
        <el-form-item label="姓名">
          <el-input  placeholder="请输入姓名" v-model="state.pagination.name" style="width: 200px;" clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="性别">
          <el-select  placeholder="请选择性别" v-model="state.pagination.sex" style="width: 150px;" clearable >
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="地址">
          <el-input  placeholder="请输入地址" v-model="state.pagination.address" style="width: 200px;" clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="状态">
          <el-select  placeholder="请选择状态" v-model="state.pagination.status" style="width: 150px;" clearable >
            <el-option label="禁用" value="0" />
            <el-option label="正常" value="1" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-button @click="load">查询</el-button>
        <el-button type="primary" class="butT" @click="handleCreate">新建</el-button>
      </el-col>

    </el-row>



  </div>

  <el-table :data="state.dataList"  style="width: 100%" >

    <el-table-column label="ID" align="center" prop="id"></el-table-column>
    <el-table-column label="用户名" align="center" prop="username"></el-table-column>
<!--    <el-table-column label="用户密码" align="center" prop="password"></el-table-column>-->
    <el-table-column label="姓名" align="center" prop="name"></el-table-column>
    <el-table-column label="性别" align="center" prop="sex"></el-table-column>
    <el-table-column label="电话号码" align="center" prop="phone" width="150"></el-table-column>
    <el-table-column label="邮箱" align="center" prop="email"></el-table-column>
    <el-table-column label="地址" align="center" prop="address"></el-table-column>
    <el-table-column label="所拥有角色" align="center" prop="roles" >
      <template v-slot="row">
        <li v-for="item in row.row.roles" :key="item">{{item.roleName}}</li>
      </template>
    </el-table-column>
    <el-table-column label="状态" align="center" prop="status"></el-table-column>
<!--    <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>-->
<!--    <el-table-column label="最后修改时间" align="center" prop="lastTime"></el-table-column>-->

    <el-table-column label="操作" align="center" fixed="right" width="180" >
      <template v-slot="{row}">
        <el-button link type="primary" size="small" @click="handleCreateRole(row)">添加角色</el-button>
        <el-button link type="primary" size="small" @click="handleOmitRole(row)">删除角色</el-button>
        <el-button link type="primary" size="small" @click="handleEidt(row)">修改</el-button>
        <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
      </template>
    </el-table-column>

  </el-table>

  <!-- 分页 -->
  <div class="pagination-container">
    <el-pagination
        class="pagiantion"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="state.pagination.currentPage"
        :page-size="state.pagination.pageSize"
        :page-sizes="[1, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.pagination.total">
    </el-pagination>
  </div>

  <!-- 新增角色弹窗-->
  <el-dialog
      v-model="state.dialogFormVisible1"
      title="添加角色"
      width="30%"
  >
    <template #footer>
        <span class="dialog-footer">
          <div class="filter-container">
    <el-row>

             <el-form-item label="所有角色">
          <el-select
              v-model="state.formData.rid"
              placeholder="请选择角色"
              multiple
              collapse-tags
              collapse-tags-tooltip
              style="width: 240px"
              clearable
          >
            <el-option
                v-for="item in state.options"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
            />
          </el-select>
           </el-form-item>

    </el-row>
  </div>
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="handleAddRole">确定</el-button>
        </span>
    </template>
  </el-dialog>

  <!-- 删除角色弹窗-->
  <el-dialog
      v-model="state.dialogFormVisible2"
      title="删除角色"
      width="30%"
  >
    <template #footer>
        <span class="dialog-footer">
          <div class="filter-container">
    <el-row>
             <el-form-item label="所有角色">
          <el-select
              v-model="state.formData.rid"
              placeholder="请选择角色"
              multiple
              collapse-tags
              collapse-tags-tooltip
              style="width: 240px"
              clearable
          >
            <el-option
                v-for="item in state.options"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
            />
          </el-select>
           </el-form-item>

    </el-row>
  </div>
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="handleDeleteRole">确定</el-button>
        </span>
    </template>
  </el-dialog>

<!--  新增用户弹窗-->
    <el-dialog
        v-model="state.dialogFormVisible"
        title="新增用户"
        width="30%">
      <template #footer>
        <span class="dialog-footer">
          <div class="filter-container">
            <el-form :model="state.formData" label-position="top" :rules="rules" ref="ruleFormRef">
    <el-row>
        <el-col span="3">
        <el-form-item label="用户名" prop="username">
          <el-input  placeholder="请输入用户名" v-model="state.formData.username"  clearable />
        </el-form-item>
      </el-col>
        <el-col span="3">
        <el-form-item label="密码" prop="password">
          <el-input  placeholder="请输入密码" v-model="state.formData.password"  clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="姓名" prop="name">
          <el-input  placeholder="请输入姓名" v-model="state.formData.name" clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="性别" prop="sex">
          <el-select  placeholder="请选择性别"  v-model="state.formData.sex" clearable >
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
      </el-col>
        <el-col span="3">
        <el-form-item label="电话号码" prop="phone">
          <el-input  placeholder="请输入电话号码" v-model="state.formData.phone"  clearable />
        </el-form-item>
      </el-col>
        <el-col span="3">
        <el-form-item label="邮箱" prop="email">
          <el-input  placeholder="请输入邮箱" v-model="state.formData.email"   clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="地址" prop="address">
          <el-input  placeholder="请输入地址" v-model="state.formData.address"  clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item label="状态" prop="status">
          <el-select  placeholder="请选择状态" v-model="state.formData.status" clearable >
            <el-option label="禁用" value="0" />
            <el-option label="正常" value="1" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    </el-form>
  </div>
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="handleAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>

<!--修改用户弹窗-->
  <el-dialog
      v-model="state.dialogFormVisible4Edit"
      title="修改用户"
      width="30%">
    <template #footer>
        <span class="dialog-footer">
          <div class="filter-container">
              <el-form :model="state.formData" label-position="top" :rules="rules" ref="ruleFormRef">
    <el-row>
        <el-col span="3">
        <el-form-item  label="用户名" prop="username">
          <el-input  placeholder="请输入用户名" v-model="state.formData.username"  clearable />
        </el-form-item>
      </el-col>
        <el-col span="3">
        <el-form-item  label="密码" prop="password">
          <el-input  placeholder="请输入密码" v-model="state.formData.password"  clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item  label="姓名" prop="name">
          <el-input  placeholder="请输入姓名" v-model="state.formData.name"  clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item  label="性别" prop="sex">
          <el-select  placeholder="请选择性别" v-model="state.formData.sex"  clearable >
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
      </el-col>
        <el-col span="3">
        <el-form-item  label="电话号码" prop="phone">
          <el-input  placeholder="请输入电话号码" v-model="state.formData.phone"  clearable />
        </el-form-item>
      </el-col>
        <el-col  span="3">
        <el-form-item  label="邮箱" prop="email">
          <el-input  placeholder="请输入邮箱" v-model="state.formData.email"  clearable />
        </el-form-item>
      </el-col>
      <el-col span="3">
        <el-form-item  label="地址" prop="address">
          <el-input  placeholder="请输入地址" v-model="state.formData.address"  clearable />
        </el-form-item>
      </el-col>

      <el-col span="3">
        <el-form-item  label="状态" prop="status">
          <el-select  placeholder="请选择状态" v-model="state.formData.status" clearable >
            <el-option label="禁用" value="0" />
            <el-option label="正常" value="1" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
   </el-form>
  </div>
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="handleUpdate">确定</el-button>
        </span>
    </template>
  </el-dialog>

</template>

<script setup>
import {reactive,ref} from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import instance from "../../../request";
const state=reactive({
  dataList: [],//表格数据
  options: [],
  selectedOptions: [],
  formData: {
    user:"",
    password:"",
    name:"",
    sex:"",
    phone:"",
    email:"",
    address:"",
    status:""
  },
  dialogFormVisible: false,//添加表单是否可见
  dialogFormVisible1: false,
  dialogFormVisible2: false,
  dialogFormVisible4Edit: false,//编辑表单是否可见
  /*rules: {//校验规则
    type: [{ required: true, message: '图书类别为必填项', trigger: 'blur' }],
    name: [{ required: true, message: '图书名称为必填项', trigger: 'blur' }]
  },*/
  pagination: {//分页相关模型数据
    currentPage: 1,//当前页码
    pageSize:5,//每页显示的记录数
    total:0,//总记录数
    name: "",
    sex: "",
    address: "",
    status: ""
  },
})

/*const ruleFormRef=ref(null);*/

const rules = reactive({
  username: [
    {required: true,message:"请输入用户名",trigger: "blur"},
  ],
  password: [
    {required: true,message:"请输入密码",trigger: "blur"},
  ],
  name: [
    {required: true,message:"请输入名字",trigger: "blur"},
  ],
  sex: [
    {required: true,message:"请选择性别",trigger: "change"},
  ],
  phone: [
    {required: true,message:"请输入电话号码",trigger: "blur"},
    {pattern:/^1\d{10}$/,message: "请输入正确的手机号",trigger: "blur"}
  ],
  email:[
    {required: true,message:"请输入邮箱",trigger: "blur"},
  ],
  address: [
    {required: true,message:"请输入地址",trigger: "blur"},
  ],
  status: [
    {required: true,message:"请选择状态",trigger: "change"},
  ]
})

//多选选择器
const getRoles=()=>{
  instance.get('/role').then(res=>{
    state.options=res.data
  })
}

//用户数据加载
const load=()=>{
  let param ="?name="+state.pagination.name;
  param +="&sex="+state.pagination.sex;
  param +="&address="+state.pagination.address;
  param +="&status="+state.pagination.status;
  instance.get('/user/'+state.pagination.currentPage+"/"+state.pagination.pageSize+param).then(res=>{
    state.pagination.total = res.data.total;
    state.dataList = res.data.list;
    for (let i = 0; i < state.dataList.length; i++) {
      if (state.dataList[i].sex==1){
        state.dataList[i].sex="男"
      }else if (state.dataList[i].sex==2){
        state.dataList[i].sex="女"
      }
    }
    for (let i = 0; i < state.dataList.length; i++) {
      if (state.dataList[i].status==0){
        state.dataList[i].status="禁用"
      }else if (state.dataList[i].status==1){
        state.dataList[i].status="正常"
      }
    }
  })
}

//切换页码
const handleCurrentChange=(currentPage)=> {
  //修改页码值为当前选中的页码值
  state.pagination.currentPage = currentPage;
  //执行查询
  load();
}

const handleSizeChange=(pageSize)=>{
  state.pagination.pageSize = pageSize;
  load();
}

//给用户添加角色
const handleAddRole=()=> {
  instance.post("/user",state.formData).then((res)=>{
    if (state.formData.rid==null || state.formData.rid==""){
      ElMessage({type: 'error', message: '角色不能为空',})
    }
    if (res.msg=="添加角色不能重复"){
      ElMessage({type: 'error', message: '添加角色不能重复',})
    }
//如果操作成功，关闭弹层，显示数据
    if(res.flag){
      state.dialogFormVisible1 = false;
      ElMessage({type: 'success', message: '添加成功',})
    }else {
      ElMessage({type: 'error', message: '添加失败',})
    }
  }).finally(()=>{
    load()
  });
}

//添加角色窗口弹出
const   handleCreateRole=(row)=> {
  getRoles()
  instance.get("/user/" + row.id).then(res => {
    if (res.flag){
      state.formData=res.data
      state.dialogFormVisible1 = true;
    }
  })
}



//给用户删除角色
const handleDeleteRole=()=> {
  instance.post("/user/delete",state.formData).then((res)=>{
    if (state.formData.rid==null || state.formData.rid==""){
      ElMessage({type: 'error', message: '角色不能为空',})
    }
    if (res.msg=="删除角色不存在"){
      ElMessage({type: 'error', message: '删除角色不存在',})
    }
//如果操作成功，关闭弹层，显示数据
    if(res.flag){
      state.dialogFormVisible2 = false;
      ElMessage({type: 'success', message: '删除成功',})
    }else {
      ElMessage({type: 'error', message: '删除失败',})
    }
  }).finally(()=>{
    load()
  });
}

//删除角色窗口弹出
const   handleOmitRole=(row)=> {
  getRoles()
  instance.get("/user/" + row.id).then(res => {
    if (res.flag){
      state.formData=res.data
      state.dialogFormVisible2 = true;
    }
  })
}


//弹出添加窗口
const handleCreate=()=> {
  state.dialogFormVisible = true;
  resetForm();
}

//重置用户数据
const resetForm=()=> {
  state.formData={};
}

//取消
const cancel=()=>{
  state.dialogFormVisible = false;
  state.dialogFormVisible4Edit = false;
  state.dialogFormVisible1 = false;
  state.dialogFormVisible2 = false;
  ElMessage({type: 'info', message: '操作取消',})
}


//添加
const handleAdd=()=> {
  if (state.formData.username == null || state.formData.username == "") {
    ElMessage({type: 'error', message: '用户名不能为空',})
  } else if (state.formData.password == null || state.formData.password == "") {
    ElMessage({type: 'error', message: '密码不能为空',})
  } else if (state.formData.name == null || state.formData.name == "") {
    ElMessage({type: 'error', message: '姓名不能为空',})
  } else if (state.formData.sex == null || state.formData.sex == "") {
    ElMessage({type: 'error', message: '性别不能为空',})
  } else if (state.formData.phone == null || state.formData.phone == "") {
    ElMessage({type: 'error', message: '电话号码不能为空',})
  } else if (state.formData.email == null || state.formData.email == "") {
    ElMessage({type: 'error', message: '邮箱不能为空',})
  } else if (state.formData.address == null || state.formData.address == "") {
    ElMessage({type: 'error', message: '地址不能为空',})
  } else if (state.formData.status == null || state.formData.status == "") {
    ElMessage({type: 'error', message: '状态不能为空',})
  } else {
    instance.post("/user/selectUsername1",state.formData).then((res) => {
      if (res.flag) {
        instance.post("/user/insert", state.formData).then((res) => {
          if (res.flag) {
            state.dialogFormVisible = false;
            ElMessage({type: 'success', message: '添加成功',})
          } else {
            ElMessage({type: 'error', message: '添加失败',})
          }
        }).finally(()=>{
          load();
        });
      } else {
        ElMessage({type: 'error', message: '用户名已存在',})
      }
    })
}
//如果操作成功，关闭弹层，显示数据
}

//弹出修改窗口
const  handleEidt=(row)=> {
  instance.get("/user/"+row.id).then(res=>{
    if(res.flag){
//展示弹层，加载数据
      state.formData=res.data
      state.dialogFormVisible4Edit = true;
    }else{
      ElMessage({type: 'error', message: '修改页面弹出失败',})
    }
  })
}

const handleUpdate=()=> {
  if (state.formData.username == null || state.formData.username == "") {
    ElMessage({type: 'error', message: '用户名不能为空',})
  } else if (state.formData.password == null || state.formData.password == "") {
    ElMessage({type: 'error', message: '密码不能为空',})
  } else if (state.formData.name == null || state.formData.name == "") {
    ElMessage({type: 'error', message: '姓名不能为空',})
  } else if (state.formData.sex == null || state.formData.sex == "") {
    ElMessage({type: 'error', message: '性别不能为空',})
  } else if (state.formData.phone == null || state.formData.phone == "") {
    ElMessage({type: 'error', message: '电话号码不能为空',})
  } else if (state.formData.email == null || state.formData.email == "") {
    ElMessage({type: 'error', message: '邮箱不能为空',})
  } else if (state.formData.address == null || state.formData.address == "") {
    ElMessage({type: 'error', message: '地址不能为空',})
  } else if (state.formData.status == null || state.formData.status == "") {
    ElMessage({type: 'error', message: '状态不能为空',})
  } else {
    instance.post("/user/selectUsername", state.formData).then((res) => {
      if (res.flag) {
        instance.put("/user", state.formData).then((res) => {
//如果操作成功，关闭弹层，显示数据
          if (res.flag) {
            state.dialogFormVisible4Edit = false;
            ElMessage({type: 'success', message: '修改成功',})
          } else {
            ElMessage({type: 'error', message: '修改失败',})
          }
        }).finally(() => {
          load();
        });
      } else {
        ElMessage({type: 'error', message: '用户名已存在',})
      }
    })
  }
}


//删除用户
const handleDelete=(row)=> {
  if (row.roles == null || row.roles == "") {
    ElMessageBox.confirm('是否删除该用户?', '提示', {
          confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning',
        }
    ).then(() => {
      instance.delete("/user/"+row.id).then((res)=>{
        if(res.flag){
          ElMessage({type: 'success', message: '删除成功',})
        }else{
          ElMessage({type: 'error', message: '删除失败',})
        }
      }).finally(()=>{
        load()
      });
    }).catch(()=>{
      ElMessage({type: 'info', message: '已取消删除',})
    });
  }else {
    ElMessage({type: 'error', message: '请先删除所拥有角色',})
  }
}

load()

</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.filter-container .el-form-item {
  margin-right: 10px;
}

.filter-container .butT {
  margin-left: 10px;
}
</style>